/**
 * Created by user on 2015/9/7.
 */

var async = require('async');
var questionStore = mongoose.model('question_store');
var Question = mongoose.model('question');
var User = mongoose.model('user');

exports.questionStoreListService = function(req ,callback) {

    var body = req.body;
    var page = req.params.page;
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;
    var totalPage = 0;

    var opt={};

    if(body.desc != null){
        opt['desc'] = new RegExp(body.desc);
    };

    if(body.storetype) opt.storetype = body.storetype;

    logger.debug(opt);
    async.series([

        function (callbackInner) {
            questionStore.count(opt, function (err, count) {

                if (err) {
                   return callbackInner(err, null);
                } else {
                    var temp = {count: count, page: Math.ceil(count/size)};
                    callbackInner(null, temp);
                }
            });
        },
        function (callbackInner) {
            questionStore.find(opt).skip(index).limit(size).populate('tag', 'value').sort('-dateCreated')
                .exec(function (err, results) {
                    if (results == undefined || results == null) {
                        var msg = {
                            "message": 'get err'
                        };
                        callbackInner(msg, null);
                    } else {

                        if(!body.model) {
                            results.forEach(function (question) {
                                question.images.forEach(function (img) {
                                    img.imageURL = 'http://' + imgHost + img.imageURL;
                                })
                            });
                        };
                        callbackInner(null, results);
                    }
                });
        }
    ], callback);

};

exports.questionStoreAddService = function(req ,callback) {

    var body = req.body;
    //body.isValid = true;
    body.desc = body.desc.replace(/[\n\r]{2,}/g, "\n").trim();

    var temp = new questionStore();
    temp.storetype = body.storetype;
    temp.category = body.category;
    //temp.contentType = body.contentType;
    temp.desc = body.desc;
    temp.images = body.images;
    logger.debug(temp);
    temp.save(callback);


};

exports.questionStoreDeleteService = function (ids, callback) {
    var queryUserIn = {};
    queryUserIn["$in"] = [];
    for (var i = 0, l = ids.length; i < l; i++) {
        queryUserIn["$in"].push(ids[i]);
    }
    logger.debug(queryUserIn);
    questionStore.remove({_id :queryUserIn}, callback);
};

exports.questionStoreEditService = function(req ,callback) {

    var body = req.body.questionStore;
    var id = req.body._id;
    //body.isValid = true;
    logger.debug(req.body);

    body.desc = body.desc.replace(/[\n\r]{2,}/g, "\n").trim();


    var opt = {
        storetype : body.storetype,
        category : body.category,
        //contentType : body.contentType,
        //images : body.images,
        desc : body.desc

    };
    logger.debug(req.body);
    questionStore.update({_id: id}, opt, callback);


};

exports.questionPostService = function(req ,callback) {

    var body = req.body;

    //Community.find({_id: body.community}, function(err, result) {
    logger.debug(body);

    var option = {};
    if (body.desc)option.desc = body.desc;
    if (body.images)option.images = body.images;
    if (body.category)option.category = body.category;
    /*  宝宝树66小区二次改造     add  guo  20170825   start   */
    if(body.topFlg)option.topFlg=body.topFlg;
    /*  宝宝树66小区二次改造     add  guo  20170825   end   */
    User.find({huanxinUserName:{$in:body.numbers}}).populate('community', '_id communityName aroundCommunity').exec(function (err, results) {

        async.each(results, function (user, callbackInner) {

            if (user.aroundCommunity)option.aroundCommunity = user.aroundCommunity;
            /*  宝宝树66小区二次改造     mod  guo  20170825   start   */
            //restClient.get('http://' + AppHost + '/rest/v1.0/System/userToken/' + user.huanxinUserName, function (data, response) {  旧

                restClient.get('http://' + AppHost + '/rest/v1.0/System/userToken/' + user.mobilePhone, function (data, response) {
                /*  宝宝树66小区二次改造     mod  guo  20170825   end   */
				var tokenData = JSON.parse(data);
                logger.debug(option);
                var args = {
                    data: option,
                    headers: {"Content-Type": "application/json"}
                };
                //发帖子
                   restClient.post('http://' + AppHost + '/rest/v1.0/Questions/newQuestion/' + tokenData.data.token + '/' + 'PC', args, function (data, res) { 
                    callbackInner(null, res);
                }).on('error', function (err) {
                    logger.error('newQuestion:' + err.message);
                    callbackInner(err, null);
                });

            });

        }, callback);

    });

};



